package com.example.myapp.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;


import com.bumptech.glide.Glide;
import com.example.myapp.R;
import com.example.myapp.TFLiteClassificationUtil;
import com.example.myapp.Utils;
import com.yalantis.ucrop.UCrop;


import cn.leancloud.LCFile;
import cn.leancloud.LCObject;
import cn.leancloud.LCQuery;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;


public class MainFragment extends Fragment {

    private TFLiteClassificationUtil tfLiteClassificationUtil;
    private ImageView imageView;
    private Uri mImageUri;
    private static final String FILE_PROVIDER_AUTHORITY = "fileprovider";
    private ImageView resultimg;
    private TextView textView;
    private ArrayList<String> classNames;
    private ActivityResultLauncher<Intent> mActivityResultLauncher;
    private ActivityResultLauncher<Intent> mCropLauncher;
    boolean cameraFlag = false;
//    private String result_url;
//    private boolean resultFlag = false;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        if (!hasPermission()) {
            requestPermission();
        }

        // 加载模型和标签
        classNames = Utils.ReadListFromFile(requireContext().getAssets(), "labels.txt");
        String classificationModelPath = requireContext().getCacheDir().getAbsolutePath() + File.separator + "mobilenet_v2.tflite";
        Utils.copyFileFromAsset(requireContext(), "mobilenet_v2.tflite", classificationModelPath);
        try {
            tfLiteClassificationUtil = new TFLiteClassificationUtil(classificationModelPath);
            Toast.makeText(requireContext(), "登录成功", Toast.LENGTH_SHORT).show();
//            Toast.makeText(requireContext(), "模型加载成功！", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
//            Toast.makeText(requireContext(), "模型加载失败！", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
            requireActivity().finish();
        }



        // 初始化 ActivityResultLauncher
        mActivityResultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == AppCompatActivity.RESULT_OK) {
                        Intent data = result.getData();
                        Uri image_uri = null;
                        if (cameraFlag) {
                            image_uri = mImageUri;
                        }
                        if (data != null && !cameraFlag) {
                            image_uri = data.getData();
                        }
                        startCrop(image_uri);
                    }
                }
        );

        mCropLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == AppCompatActivity.RESULT_OK && result.getData() != null) {
                        Uri resultUri = UCrop.getOutput(result.getData());
                        try {
                            // 获取图像信息
                            InputStream inputStream = requireContext().getContentResolver().openInputStream(resultUri);
//                                InputStream inputStream = requireContext().getContentResolver().openInputStream(destinationUri);
                            imageView.setImageBitmap(BitmapFactory.decodeStream(inputStream));
//                                long start = System.currentTimeMillis();
                            InputStream inputStream2 = requireContext().getContentResolver().openInputStream(resultUri);
//                                InputStream inputStream2 = requireContext().getContentResolver().openInputStream(destinationUri);
                            //获取分类结果
                            float[] results = tfLiteClassificationUtil.predictImage(inputStream2);
//                                long end = System.currentTimeMillis();
                            String show_text =
//                                        "预测结果标签：" + (int) results[0] + "\n" +
                                    "名称：" + classNames.get((int) results[0]) +
                                            "\n概率：" + results[1] +
                                            "\n如果识别不准确,可以上传其他角度的图片";
                            //显示分类结果
                            textView.setText(show_text);
                            //设置再利用示范图片
                            String type = getImageType(classNames.get((int) results[0]));
                            String result_img_name = "r" + String.valueOf((int) results[0]);
//                                String result_img_name = "r" + String.valueOf((int) results[0]) + ".jpg";
                            setImageView(result_img_name,type, resultimg);
                            inputStream.close();
                            inputStream2.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
        );

        // 获取控件
        Button selectImgBtn = view.findViewById(R.id.select_img_btn);
        Button takePhotoBtn = view.findViewById(R.id.take_photo_btn);

        imageView = view.findViewById(R.id.image_view);
        resultimg = view.findViewById(R.id.result_img_view);
        textView = view.findViewById(R.id.result_text);
        selectImgBtn.setOnClickListener(v -> {
            // 打开相册
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            cameraFlag = false;
            mActivityResultLauncher.launch(intent);
        });
        takePhotoBtn.setOnClickListener(v -> {
            //打开摄像头
            Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//打开相机的Intent
            File imageFile = createImageFile();//创建用来保存照片的文件
            if (imageFile != null) {
                mImageUri = FileProvider.getUriForFile(requireContext(), FILE_PROVIDER_AUTHORITY, imageFile);
                takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);//将用于输出的文件Uri传递给相机
                cameraFlag = true;
                mActivityResultLauncher.launch(takePhotoIntent);
            }
        });

//        if(resultFlag){
//            requireActivity().runOnUiThread(() -> {
//            Glide.with(requireContext())
//                    .load(result_url)
//                    .into(resultimg);
//            });
//        }



        return view;
    }

//    // 根据相册的Uri获取图片的路径
//    public static String getPathFromURI(Context context, Uri uri) {
//        String result;
//        Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
//        if (cursor == null) {
//            result = uri.getPath();
//        } else {
//            cursor.moveToFirst();
//            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
//            result = cursor.getString(idx);
//            cursor.close();
//        }
//        return result;
//    }

    // check had permission
    private boolean hasPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return requireContext().checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED &&
                    requireContext().checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                    requireContext().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        } else {
            return true;
        }
    }

    // request permission
    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.CAMERA,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }
    }

//    private void setImageView(String imageName, String type, ImageView imageView) {
//
//        // 2. 查询 LeanCloud 的 _File 表
//        LCQuery<LCFile> query = new LCQuery<>("_File");
//        query.whereEqualTo("name", imageName);
//        query.getFirstInBackground().subscribe(new Observer<LCFile>() {
//            @Override
//            public void onSubscribe(Disposable d) {
//                // 可在此处管理 Disposable（如存入 CompositeDisposable）
//            }
//
//            @Override
//            public void onNext(LCFile lcFile) {
//                if (lcFile != null && isAdded()) { // 检查 Fragment 是否已附加
//                    result_url = lcFile.getUrl();
//                    Toast.makeText(requireContext(), result_url, Toast.LENGTH_SHORT).show();
//                    resultFlag = true;
//                    // 3. 使用 Glide 在主线程加载图片
//                }
//            }
//
//            @Override
//            public void onError(Throwable e) {
//                requireActivity().runOnUiThread(() -> {
//                    Toast.makeText(requireContext(), "图片加载失败", Toast.LENGTH_SHORT).show();
//                });
//            }
//
//            @Override
//            public void onComplete() {
//                // 查询完成
//            }
//        });
//    }


    private void setImageView(String imageName, String type, ImageView imageView) {


        // 根据图片名获得资源 ID
        int resourceId = getResources().getIdentifier(imageName, "drawable", requireContext().getPackageName());
        if (resourceId != 0) { // 如果资源 ID 不为 0，则图片存在
            imageView.setImageResource(resourceId); // 设置 ImageView 的图片
        } else {
            // 图片不存在，根据垃圾类型提供处理方法
            Toast.makeText(requireContext(), "当前暂无该垃圾处理方法", Toast.LENGTH_SHORT).show();
            switch (type){
                case "厨余垃圾":
                    imageView.setImageResource(R.drawable.food_waste); // 设置厨余垃圾默认图片
                    break;
                case "可回收物":
                    imageView.setImageResource(R.drawable.recyclable); // 设置可回收物默认图片
                    break;
                case "有害垃圾":
                    imageView.setImageResource(R.drawable.hazardous_waste); // 设置有害垃圾默认图片
                    break;
                case "其他垃圾":
                    imageView.setImageResource(R.drawable.residual_waste); // 设置其他垃圾默认图片
                    break;
            }
        }
    }

    private File createImageFile() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = requireContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File imageFile = null;
        try {
            imageFile = File.createTempFile(imageFileName, ".jpg", storageDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageFile;
    }

    public static String getImageType(String input) {
        if (input == null) {
            return null;
        }
        int index = input.indexOf('_');
        if (index == -1) {
            return input;  // 如果没有找到'_'，则返回整个字符串
        }
        return input.substring(0, index);
    }

    private void startCrop(Uri sourceUri){
        File cacheDir = requireContext().getExternalCacheDir() != null ?
                requireContext().getExternalCacheDir() : requireContext().getCacheDir();
        Uri destinationUri = Uri.fromFile(new File(cacheDir, "cropped_image.jpg"));

        UCrop.Options options = new UCrop.Options();
        //让用户可以自由调整范围
        options.setFreeStyleCropEnabled(true);
        //不显示网格线
        options.setShowCropGrid(false);

        Intent intent = UCrop.of(sourceUri, destinationUri)
                .withAspectRatio(16, 9)
                .withOptions(options)
                .getIntent(requireContext());

        mCropLauncher.launch(intent);
    }
}
